<template>
  <div class="logs-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>日志管理</h2>
      <p>查看系统日志和客户端日志</p>
    </div>

    <!-- 日志类型切换 -->
    <el-tabs v-model="activeTab" @tab-change="handleTabChange" class="log-tabs">
      <el-tab-pane label="系统日志" name="system">
        <div class="tab-content">
          <!-- 筛选工具栏 -->
          <div class="toolbar">
            <div class="toolbar-left">
              <el-select
                v-model="systemFilters.level"
                placeholder="日志级别"
                clearable
                style="width: 150px"
                @change="loadSystemLogs"
              >
                <el-option label="全部" value="" />
                <el-option label="INFO" value="info" />
                <el-option label="WARN" value="warn" />
                <el-option label="ERROR" value="error" />
              </el-select>

              <el-select
                v-model="systemFilters.action"
                placeholder="操作类型"
                clearable
                style="width: 150px; margin-left: 12px"
                @change="loadSystemLogs"
              >
                <el-option label="全部" value="" />
                <el-option label="登录" value="login" />
                <el-option label="文件操作" value="file" />
                <el-option label="用户管理" value="user" />
                <el-option label="系统配置" value="config" />
              </el-select>

              <el-date-picker
                v-model="systemFilters.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="margin-left: 12px"
                @change="loadSystemLogs"
              />
            </div>

            <div class="toolbar-right">
              <el-input
                v-model="systemFilters.keyword"
                placeholder="搜索日志内容"
                :prefix-icon="Search"
                clearable
                style="width: 250px"
                @input="handleSystemSearch"
              />
              <el-button :icon="Refresh" @click="loadSystemLogs" style="margin-left: 12px">
                刷新
              </el-button>
              <el-button :icon="Download" @click="handleExportLogs('system')">
                导出
              </el-button>
            </div>
          </div>

          <!-- 系统日志列表 -->
          <el-table
            :data="systemLogs"
            v-loading="systemLoading"
            class="log-table"
            :row-class-name="getSystemLogRowClass"
          >
            <el-table-column label="时间" width="180">
              <template #default="{ row }">
                {{ formatTime(row.created_at) }}
              </template>
            </el-table-column>

            <el-table-column label="级别" width="100">
              <template #default="{ row }">
                <el-tag :type="getLogLevelType(row.level)" size="small">
                  {{ row.level.toUpperCase() }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column label="操作" width="120" prop="action" />

            <el-table-column label="操作人" width="150" prop="admin_username" />

            <el-table-column label="IP地址" width="150" prop="ip_address" />

            <el-table-column label="详情" min-width="300">
              <template #default="{ row }">
                <div class="log-detail">{{ row.details }}</div>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination">
            <el-pagination
              v-model:current-page="systemPage"
              v-model:page-size="systemPageSize"
              :page-sizes="[20, 50, 100, 200]"
              :total="systemTotal"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSystemSizeChange"
              @current-change="handleSystemPageChange"
            />
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="客户端日志" name="client">
        <div class="tab-content">
          <!-- 筛选工具栏 -->
          <div class="toolbar">
            <div class="toolbar-left">
              <el-select
                v-model="clientFilters.level"
                placeholder="日志级别"
                clearable
                style="width: 150px"
                @change="loadClientLogs"
              >
                <el-option label="全部" value="" />
                <el-option label="INFO" value="info" />
                <el-option label="WARN" value="warn" />
                <el-option label="ERROR" value="error" />
              </el-select>

              <el-select
                v-model="clientFilters.userId"
                placeholder="选择用户"
                clearable
                filterable
                style="width: 200px; margin-left: 12px"
                @change="loadClientLogs"
              >
                <el-option
                  v-for="user in userList"
                  :key="user.id"
                  :label="user.username"
                  :value="user.id"
                />
              </el-select>

              <el-date-picker
                v-model="clientFilters.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="margin-left: 12px"
                @change="loadClientLogs"
              />
            </div>

            <div class="toolbar-right">
              <el-input
                v-model="clientFilters.keyword"
                placeholder="搜索日志内容"
                :prefix-icon="Search"
                clearable
                style="width: 250px"
                @input="handleClientSearch"
              />
              <el-button :icon="Refresh" @click="loadClientLogs" style="margin-left: 12px">
                刷新
              </el-button>
              <el-button :icon="Download" @click="handleExportLogs('client')">
                导出
              </el-button>
            </div>
          </div>

          <!-- 客户端日志列表 -->
          <el-table
            :data="clientLogs"
            v-loading="clientLoading"
            class="log-table"
            :row-class-name="getClientLogRowClass"
          >
            <el-table-column label="时间" width="180">
              <template #default="{ row }">
                {{ formatTime(row.received_at) }}
              </template>
            </el-table-column>

            <el-table-column label="级别" width="100">
              <template #default="{ row }">
                <el-tag :type="getLogLevelType(row.level)" size="small">
                  {{ row.level.toUpperCase() }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column label="用户" width="150" prop="username" />

            <el-table-column label="客户端ID" width="180" prop="client_id" />

            <el-table-column label="详情" min-width="300">
              <template #default="{ row }">
                <div class="log-detail">{{ row.message }}</div>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination">
            <el-pagination
              v-model:current-page="clientPage"
              v-model:page-size="clientPageSize"
              :page-sizes="[20, 50, 100, 200]"
              :total="clientTotal"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleClientSizeChange"
              @current-change="handleClientPageChange"
            />
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh, Download } from '@element-plus/icons-vue'
import axios from '@/api'

// 数据状态
const activeTab = ref('system')
const userList = ref([])

// 系统日志
const systemLogs = ref([])
const systemLoading = ref(false)
const systemPage = ref(1)
const systemPageSize = ref(20)
const systemTotal = ref(0)
const systemFilters = reactive({
  level: '',
  action: '',
  keyword: '',
  dateRange: []
})

// 客户端日志
const clientLogs = ref([])
const clientLoading = ref(false)
const clientPage = ref(1)
const clientPageSize = ref(20)
const clientTotal = ref(0)
const clientFilters = reactive({
  level: '',
  userId: '',
  keyword: '',
  dateRange: []
})

// 生命周期
onMounted(() => {
  loadSystemLogs()
  loadUserList()
})

// 方法
const handleTabChange = (tab) => {
  if (tab === 'client' && clientLogs.value.length === 0) {
    loadClientLogs()
  }
}

const loadSystemLogs = async () => {
  systemLoading.value = true
  try {
    const params = {
      page: systemPage.value,
      limit: systemPageSize.value,
      level: systemFilters.level,
      action: systemFilters.action,
      keyword: systemFilters.keyword
    }

    if (systemFilters.dateRange && systemFilters.dateRange.length === 2) {
      params.start_date = systemFilters.dateRange[0].toISOString()
      params.end_date = systemFilters.dateRange[1].toISOString()
    }

    const response = await axios.get('/api/logs/system', { params })
    systemLogs.value = response.data.data.logs || []
    systemTotal.value = response.data.data.total || 0
  } catch (error) {
    console.error('加载系统日志失败:', error)
    ElMessage.error('加载系统日志失败')
  } finally {
    systemLoading.value = false
  }
}

const loadClientLogs = async () => {
  clientLoading.value = true
  try {
    const params = {
      page: clientPage.value,
      limit: clientPageSize.value,
      level: clientFilters.level,
      user_id: clientFilters.userId,
      keyword: clientFilters.keyword
    }

    if (clientFilters.dateRange && clientFilters.dateRange.length === 2) {
      params.start_date = clientFilters.dateRange[0].toISOString()
      params.end_date = clientFilters.dateRange[1].toISOString()
    }

    const response = await axios.get('/api/logs/client', { params })
    clientLogs.value = response.data.data.logs || []
    clientTotal.value = response.data.data.total || 0
  } catch (error) {
    console.error('加载客户端日志失败:', error)
    ElMessage.error('加载客户端日志失败')
  } finally {
    clientLoading.value = false
  }
}

const loadUserList = async () => {
  try {
    const response = await axios.get('/api/users', {
      params: { page: 1, limit: 1000 }
    })
    userList.value = response.data.data.users || []
  } catch (error) {
    console.error('加载用户列表失败:', error)
  }
}

const handleSystemSearch = () => {
  systemPage.value = 1
  loadSystemLogs()
}

const handleClientSearch = () => {
  clientPage.value = 1
  loadClientLogs()
}

const handleSystemSizeChange = (val) => {
  systemPageSize.value = val
  loadSystemLogs()
}

const handleSystemPageChange = (val) => {
  systemPage.value = val
  loadSystemLogs()
}

const handleClientSizeChange = (val) => {
  clientPageSize.value = val
  loadClientLogs()
}

const handleClientPageChange = (val) => {
  clientPage.value = val
  loadClientLogs()
}

const handleExportLogs = async (type) => {
  try {
    const endpoint = type === 'system' ? '/api/logs/system/export' : '/api/logs/client/export'
    const filters = type === 'system' ? systemFilters : clientFilters

    const params = {
      level: filters.level,
      keyword: filters.keyword
    }

    if (type === 'system') {
      params.action = systemFilters.action
    } else {
      params.user_id = clientFilters.userId
    }

    if (filters.dateRange && filters.dateRange.length === 2) {
      params.start_date = filters.dateRange[0].toISOString()
      params.end_date = filters.dateRange[1].toISOString()
    }

    const response = await axios.get(endpoint, {
      params,
      responseType: 'blob'
    })

    const url = window.URL.createObjectURL(new Blob([response.data]))
    const link = document.createElement('a')
    link.href = url
    const filename = `${type}_logs_${new Date().getTime()}.csv`
    link.setAttribute('download', filename)
    document.body.appendChild(link)
    link.click()
    link.remove()
    window.URL.revokeObjectURL(url)

    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 工具函数
const getLogLevelType = (level) => {
  const typeMap = {
    info: 'success',
    warn: 'warning',
    error: 'danger'
  }
  return typeMap[level?.toLowerCase()] || 'info'
}

const getSystemLogRowClass = ({ row }) => {
  if (row.level === 'error') return 'error-row'
  if (row.level === 'warn') return 'warn-row'
  return ''
}

const getClientLogRowClass = ({ row }) => {
  if (row.level === 'error') return 'error-row'
  if (row.level === 'warn') return 'warn-row'
  return ''
}

const formatTime = (time) => {
  if (!time) return '-'
  const date = new Date(time)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  const second = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`
}
</script>

<style scoped>
.logs-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: calc(100vh - 60px);
}

.page-header {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 16px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #333;
}

.page-header p {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.log-tabs {
  background: white;
  padding: 0 20px;
  border-radius: 8px;
}

.log-tabs :deep(.el-tabs__header) {
  margin-bottom: 0;
}

.tab-content {
  padding: 20px 0;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 16px;
  background: #f5f5f5;
  border-radius: 8px;
}

.toolbar-left {
  display: flex;
  align-items: center;
}

.toolbar-right {
  display: flex;
  align-items: center;
}

.log-table {
  margin-bottom: 16px;
}

.log-table :deep(.error-row) {
  background: #fef0f0;
}

.log-table :deep(.warn-row) {
  background: #fdf6ec;
}

.log-detail {
  word-break: break-all;
  line-height: 1.6;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  padding: 16px 0;
}
</style>
